<template>
  <div>
    <el-row>
      <el-col :span="20">
        <div id="mapDiv" style="height: 700px"></div>
      </el-col>
      <el-col :span="4">
        <br>
        <br>
        <br>
        <el-form ref="form" :model="form" label-width="60px">
          <el-form-item label="起点: ">
            <el-select
              v-model="form.start"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="startMethod"
              :loading="startLoading">
              <el-option
                v-for="item in startList"
                :key="item.id"
                :label="item.cityAllName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起点: ">
            <el-select
              v-model="form.end"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="endMethod"
              :loading="endLoading">
              <el-option
                v-for="item in endList"
                :key="item.id"
                :label="item.cityAllName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="距离: " v-if="this.distance != ''">
            <span>
              <b>
                {{distance}}km
              </b>
            </span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { loadCss, setDefaultOptions, loadModules } from "esri-loader";
  export default {
    name: "index",
    data() {
      return {
        map: {},
        view: {},
        routeLayer: {},
        layer: {},
        routeTask: {},
        routeParams: {},
        stopSymbol: {},
        routeSymbol: {},
        Graphic: {},
        form: {
          startX: 113.468,
          startY: 23.555,
          endX: 110.719,
          endY: 21.435,
          start: "",
          end: ""
        },
        startList: [],
        startLoading: false,
        endList: [],
        endLoading: false,
        distance: ""
      }
    },
    created() {
      this.initMap();
    },
    methods: {
      initMap() {
        setDefaultOptions({url: 'https://js.arcgis.com/4.8/'});
        loadCss('https://js.arcgis.com/4.18/esri/themes/light/main.css');
        loadModules([
          "esri/Map",
          "esri/config",
          "esri/views/MapView",
          "esri/layers/MapImageLayer",
          "esri/geometry/Extent",
          "esri/Graphic",
          "esri/layers/GraphicsLayer",
          "esri/tasks/RouteTask",
          "esri/tasks/support/RouteParameters",
          "esri/tasks/support/FeatureSet",
          "dojo/on",
          "dojo/domReady"
        ], { css: true }).then(([Map,
                                          esriConfig,
                                          MapView,
                                          MapImageLayer,
                                          Extent,
                                          Graphic,
                                          GraphicsLayer,
                                          RouteTask,
                                          RouteParameters,
                                          FeatureSet,
                                          on]) => {
          this.Graphic = Graphic;
          esriConfig.request.corsEnabledServers.push("localhost:6080");//设置地图服务器已允许跨域
          this.routeLayer = new GraphicsLayer();
          //layer为原始路网数据层，可以不添加
          this.layer=new MapImageLayer({
            url:"http://localhost:6080/arcgis/rest/services/arcMap_search/MapServer"
          });
          this.map = new Map({
            basemap: "streets",
            layers:[this.layer,this.routeLayer]
          });
          //起始点样式
          this.stopSymbol = {
            type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
            style: "cross",
            size: 15,
            outline: { // autocasts as new SimpleLineSymbol()
              width: 4
            }
          };
          //返回路线样式
          this.routeSymbol = {
            type: "simple-line", // autocasts as SimpleLineSymbol()
            color: [97, 165, 38, 1],
            width: 5
          };
          //查询参数
          this.routeParams = new RouteParameters({
            stops: new FeatureSet(),//停靠点
            outSpatialReference: { // 输出投影
              wkid: 3857
            }
          });
          this.routeTask = new RouteTask({
            url: "http://localhost:6080/arcgis/rest/services/arcMap_search/NAServer/road"
          });
          // 二维视图
          this.view = new MapView({
            map: this.map,
            container: "mapDiv"
          });

          this.view.ui.remove("attribution");//移除底部ESRI logo
          //初始化位置
          const viewTemp = this.view;
          this.view.when(function () {
            viewTemp.extent = new Extent({
              xmin: 9170813.75677811,
              ymin: 5213570.648163019,
              xmax: 1.521319180644298E7,
              ymax: 8073715.481906304,
              spatialReference: {
                wkid: 3857
              }
            })
          });
          //点击地图添加停靠点
          on(this.view, "click", this.addStop);
        })
      },
      addStop(event) {
        // 将停靠点添加在地图上
        var stop = new this.Graphic({
          geometry: event.mapPoint,
          symbol: this.stopSymbol
        });
        this.routeLayer.add(stop);

        // 将点击点加入到计算参数中，超过两个点则开始计算路线
        this.routeParams.stops.features.push(stop);
        if (this.routeParams.stops.features.length === 2) {
          // 进行查询
          this.routeTask.solve(this.routeParams).then(this.showRoute,this.logError);
        }
      },
      showRoute(data) {
        console.log("data");
        console.log(data);
        this.distance = data.routeResults[0].route.attributes[`Total_长度`].toFixed(2);
        var routeResult = data.routeResults[0].route;
        routeResult.symbol = this.routeSymbol;
        this.routeLayer.add(routeResult);
      },
      logError(error) {
        console.error(error);
      },
      onSubmit() {
        if (this.form.start === "" || this.form.end === "") {
          return;
        }
        let startValue = {};
        let endValue = {};
        for (let i = 0; i < this.startList.length; i++) {
          if (this.form.start === this.startList[0].id) {
            startValue = this.startList[0];
          }
        }
        for (let i = 0; i < this.endList.length; i++) {
          if (this.form.end === this.endList[0].id) {
            endValue = this.endList[0];
          }
        }
        const start = {
          type: "point",
          longitude: startValue.longitude,
          latitude: startValue.latitude
        };
        const end = {
          type: "point",
          longitude: endValue.longitude,
          latitude: endValue.latitude
        };
        const startStop = new this.Graphic({
          geometry: start,
          symbol: this.stopSymbol
        });
        const endStop = new this.Graphic({
          geometry: end,
          symbol: this.stopSymbol
        });
        this.routeLayer.add(startStop);
        this.routeLayer.add(endStop);
        this.routeParams.stops.features.push(startStop);
        this.routeParams.stops.features.push(endStop);
        this.routeTask.solve(this.routeParams).then(this.showRoute,this.logError);
      },
      async startMethod(query) {
        if (query !== '') {
          this.startLoading = true;
          const paramObj = {};
          paramObj.cityName = query;
          const result = await this.$api.city.query(paramObj);
          if (result.code === 0) {
            this.startLoading = false;
            this.startList = result.data;
          } else {
            this.startList = [];
          }
        }
      },
      async endMethod(query) {
        if (query !== '') {
          this.endLoading = true;
          const paramObj = {};
          paramObj.cityName = query;
          const result = await this.$api.city.query(paramObj);
          if (result.code === 0) {
            this.endLoading = false;
            this.endList = result.data;
          } else {
            this.endList = [];
          }
        }
      }
    }
  }
</script>

<style scoped>
</style>
